package com.hmdp.service.impl;

import com.hmdp.config.RedissionConfig;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private IVoucherOrderService voucherOrderService;

    @Resource
    private RedisIdWorker redisIdWorker;

    @Autowired
    @Lazy
    private VoucherOrderServiceImpl voucherOrderServiceImpl;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;

    //定义Lua脚本
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    //阻塞队列,用于存储需要完成的订单操作
    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024*1024);
    //创建线程池，用来开辟新线程来处理阻塞队列中的订单操作
    private final static ExecutorService  SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    IVoucherOrderService proxy;

    //在类初始化之后执行，因为当这个类初始化好之后，随时都有可能有订单处理操作
    @PostConstruct
    private void init() {
        SECKILL_ORDER_EXECUTOR.submit(new VorcherOrderHandler());
    }
    //用于线程池处理的任务
    //当初始化完毕后，就会去队列中去拿信息
    private class VorcherOrderHandler implements Runnable {

        @Override
        public void run() {
            while(true) {
                try {
                    //获取队列中订单信息
                    VoucherOrder voucherOrder = orderTasks.take();
                    //创建订单操作
                    handleVoucherOrder(voucherOrder);
                } catch (InterruptedException e) {
                    log.error("处理订单异常",e);
                }
            }
        }

        private void handleVoucherOrder(VoucherOrder voucherOrder) {
            //用户id
            Long userId = voucherOrder.getUserId();
            //获取Redission分布式锁
            RLock redisLock = redissonClient.getLock("lock:order:" + userId);
            // 尝试获取锁
            boolean isLock = redisLock.tryLock();
            // 4.判断是否获得锁成功
            if (!isLock) {
                // 获取锁失败，直接返回失败或者重试
                log.error("不允许重复下单！");
                return;
            }
            try {
                //注意：由于是spring的事务是放在threadLocal中，此时的是多线程，事务会失效
                voucherOrderServiceImpl.createVoucherOrder(voucherOrder);
            } finally {
                // 释放锁
                redisLock.unlock();
            }
        }
    }

    @Override
    public Result seckillVoucher(Long voucherId) {
        //用户id
        Long userId = UserHolder.getUser().getId();
        //订单id
        long orderId = redisIdWorker.nextId("order");
        //执行Lua脚本
        Long result = stringRedisTemplate.execute(SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString(), String.valueOf(orderId));
        int r = result.intValue();
        if(r != 0){
            //不为0，代表没有购买资格
            return Result.fail((r==1? "库存不足":"不能重复下单"));
        }
        //保存到阻塞队列
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
        voucherOrder.setId(orderId);
        orderTasks.add(voucherOrder);
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        return Result.ok(orderId);
    }

    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getUserId();
        Long voucherId = voucherOrder.getVoucherId();
        //实现一人一单,在这里判断该用户是否已经存在订单
        Integer count = voucherOrderService.query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        if (count > 0) {
            //该用户已经下过单了
            log.error("用户已经购买过了!");
            return;
        }
        //1.2 修改优惠卷数据，库存减少
        //每次在修改库存之前先判断当前库所是否还有，如果存在库存再执行。
        boolean success = seckillVoucherService.update().
                setSql("stock = stock - 1").
                eq("voucher_id", voucherId).
                gt("stock", 0).  //where id = ? and stock >0
                        update();
        if (!success) {
            //库存不足
            log.error("库存不足");
            return;
        }
        voucherOrderService.save(voucherOrder);
    }


/*    @Override
    public Result seckillVoucher(Long voucherId) {
        //根据优惠卷id查询优惠卷数据
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        //1.修改秒杀优惠卷库存
        //1.1判断优惠券是否有效
        LocalDateTime now = LocalDateTime.now();
        if(voucher.getBeginTime().isAfter(now) || voucher.getEndTime().isBefore(now)){
            //不在有效期范围内
            return Result.fail("优惠券不在有效期范围内");
        }
        //1.2判断优惠卷库存
        if (voucher.getStock() < 1) {
            // 库存不足
            return Result.fail("库存不足！");
        }
        Long userId = UserHolder.getUser().getId();
        //创建锁对象
//        SimpleRedisLock lock = new SimpleRedisLock("order:" + userId, stringRedisTemplate);
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        //获取锁
//        boolean isLock = lock.tryLock(10L);
        boolean isLock = lock.tryLock();
        if (!isLock) {
            //获取失败，直接返回错误
            return Result.fail("不能重复下单");
        }
        //获取事务相关动态代理对象
//      IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();//不知道为什么出错，先使用自注入的方法实现动态代理。

//        synchronized (userId.toString().intern()){
//            return voucherOrderServiceImpl.createVoucherOrder(voucherId);
//        }
        try {
            return voucherOrderServiceImpl.createVoucherOrder(voucherId);
        } finally {
            //释放锁
            lock.unlock();
        }
    }*/

/*    @Transactional
    public Result createVoucherOrder(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        //实现一人一单,在这里判断该用户是否已经存在订单
        Integer count = voucherOrderService.query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        if (count > 0) {
            //该用户已经下过单了
            return Result.fail("每人仅限一单！");
        }
        //1.2 修改优惠卷数据，库存减少
        //每次在修改库存之前先判断当前库所是否还有，如果存在库存再执行。
        boolean success = seckillVoucherService.update().
                setSql("stock = stock - 1").
                eq("voucher_id", voucherId).
                gt("stock", 0).  //where id = ? and stock >0
                        update();
        if (!success) {
            //库存不足
            return Result.fail("库存不足！");
        }
        //2.添加优惠卷订单
        VoucherOrder voucherOrder = new VoucherOrder();
        //2.1订单id，利用全局id生成器
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
        //2.2优惠券id
        voucherOrder.setVoucherId(voucherId);
        //2.3用户id
        voucherOrder.setUserId(UserHolder.getUser().getId());
        voucherOrderService.save(voucherOrder);
        return Result.ok(orderId);
    }*/
}
